// pages/tabBar/enterprise/enterprise.js
import { request, upRequest, wxuuid,getTotalSize } from "../../../../../utils/util.js"
const { $Message } = require('../../../../../dist/base/index');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],     //文件列表
    folderValue: "",   //似乎没用
    classTip: "toolTip-hidden",  //似乎没用
    isLoading: true,    //加载动画
    classifyType: "user", //类型显示
    visible1: false, //加号显示
    actions1: [      //加号内容
      {
        name: '从本地选择图片上传',
        icon: 'picture'
      },
      {
        name: '从会话中选择文件上传',
        icon: 'interactive'
      },
      {
        name: '新建文件夹',
        color: "#487ff8"
      },
    ],
    visibleCreate: false  //似乎没用
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setStorageSync('location', "user")
    if(app.globalData.isNeedOnshow){
      this.getFileList();
      wx.pageScrollTo({
        scrollTop:0,
        duration: 0,
      })
    }
    app.globalData.isNeedOnshow = true
   

  },

  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const that = this
    const param = {
      type: this.data.classifyType
    }
    request("GET", "/api/service/catalog", param).then(res => {
      that.setData({
        fileList: res.data.data
      })
      wx.stopPullDownRefresh()
   
    })


  },

  
  /**
   * 获取数据的封装
   */
  getFileList() {

    const that = this
    const param = {
      type: this.data.classifyType
    }
    request("GET", "/api/service/catalog", param).then(res => {
      that.setData({
        fileList: res.data.data,
        isLoading: false
      })

    })
  },
  /**
     * 打开上啦菜单
     */
  add() {
    this.setData({
      visible1: true
    });
  },
  /**
   * 关闭上啦菜单
   */
  handleCancel1() {
    this.setData({
      visible1: false
    });
  },
  /**
   * 上啦框里的各个事件
   * @param {}} param0 
   */
  handleClickItem1({ detail }) {
    const that = this
    const userInfo = wx.getStorageSync('userInfo')
    const parent = userInfo.catalog
    if (detail.index == 0) {
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          const fileRes = res
          // tempFilePath可以作为img标签的src属性显示图片
          const file_size = getTotalSize(res)
          const availableCapacity = wx.getStorageSync('availableCapacity') //获取可用容量
          if(file_size > availableCapacity){
            wx.showToast({
              title: '个人容量不足',
              icon:"none"
            })
            that.handleCancel1();
            return
          }
          const tempFilePaths = res.tempFilePaths
          const length = tempFilePaths.length
          let successNum = 0
          const verify_file_hash = wxuuid()
          const param = {
            file_hash: verify_file_hash,
            file_catalog: that.data.parent,
            file_size:file_size
          }
          that.handleCancel1();
          request("POST", "/api/upload/verify/", param)
            .then(res => {
              if(res.statusCode === 200){
                if(res.data.detail){
                  wx.showToast({
                    title: res.data.detail,
                    icon:'none'
                  })
                 
                  return
                }
                $Message({
                  content: `正在上传(0/${length})`,
                  duration: 999
                });
                for (let i = 0; i < length; i++) {
                  const chunk_hash = wxuuid() + "-0"
                  const file_hash = wxuuid()
                  const param = {
                    chunk_hash: chunk_hash,
                    file_hash: file_hash
                  }
                  const file_name = file_hash.split("-")[4]
                  const size = fileRes.tempFiles[i].size
                  upRequest("/api/upload/upload_chunk/", "chunk", tempFilePaths[i], param).then(res => {
  
                    if (res.statusCode === 200) {
                      const params = {
                        total_size: size,
                        file_catalog: parent,
                        file_hash: file_hash,
                        file_name: file_name + ".jpg",
                        version: 1.0
                      }
                      request("POST", "/api/upload/merge/", params).then(res => {
                        successNum = successNum + 1
                        $Message({
                          content: `正在上传(${successNum}/${length})`,
                          duration: 999
                        });
                        if (successNum === length) {
                          const showMsg = setTimeout(() => {
                            $Message({
                              content: "上传完成",
                              type: 'success',
                              duration: 2
                            });
                            that.getFileList();
                            clearTimeout(showMsg)
                          }, 500)
                        }
                      })
                    }
                  }).catch(error => {
  
                  })
                }
              }
            })

        }
      })
    } else if (detail.index == 1) {
      wx.chooseMessageFile({
        count: 9,
        type: 'all',
        success(res) {
          const file_size = getTotalSize(res)
          const availableCapacity = wx.getStorageSync('availableCapacity') //获取可用容量
          if(file_size > availableCapacity){
            wx.showToast({
              title: '个人容量不足',
              icon:"none",
              duration:1500
            })
            that.handleCancel1();
            return
          }
          const tempFiles = res.tempFiles
          const length = tempFiles.length
          let successNum = 0
          const verify_file_hash = wxuuid()
          const param = {
            file_hash: verify_file_hash,
            file_catalog: that.data.parent,
            file_size:file_size
          }
         
          that.handleCancel1();
          request("POST", "/api/upload/verify/", param)
          .then(res =>{
            if(res.statusCode === 200){
              if(res.data.detail){
                wx.showToast({
                  title: res.data.detail,
                  icon:'none'
                })
                return
              }
              $Message({
                content: `正在上传(0/${length})`,
                duration: 999
              });
              for (let i = 0; i < length; i++) {
                const chunk_hash = wxuuid() + "-0"
                const file_hash = wxuuid()
                const param = {
                  chunk_hash: chunk_hash,
                  file_hash: file_hash
                }
                const file_name = tempFiles[i].name
                const size = tempFiles[i].size
                upRequest("/api/upload/upload_chunk/", "chunk", tempFiles[i].path, param).then(res => {
    
                  if (res.statusCode === 200) {
                    const params = {
                      total_size: size,
                      file_catalog: parent,
                      file_hash: file_hash,
                      file_name: file_name,
                      version: 1.0
                    }
                    request("POST", "/api/upload/merge/", params).then(res => {
                      successNum = successNum + 1
                      $Message({
                        content: `正在上传(${successNum}/${length})`,
                        duration: 999
                      });
                      if (successNum === length) {
                        const showMsg =setTimeout(() => {
                          $Message({
                            content: "上传完成",
                            type: 'success',
                            duration: 2
                          });
                          that.getFileList();
                          clearTimeout(showMsg)
                        }, 500)
                      }
                    })
                  }
                }).catch(error => {
    
                })
              }
            }
          })


          
        },
        fail() {

        }
      })
    } else {
      this.selectComponent("#inputModal").setShow()
    }
  },
  /**
   * 测试用调用展示MSg
   * @param {*} e 
   */
  showMsg: function (e) {

    const mes = e.detail
    $Message({
      content: mes
    });
  },
  multipleChoice(e){
    this.selectComponent("#halfScreen").showHalfScreen()
  }


})